package com.hongxun.design.acceptance.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSON;
import com.hongxun.design.MyApp;
import com.hongxun.design.R;
import com.hongxun.design.acceptance.adapter.ExLvAdapter;
import com.hongxun.design.acceptance.mode.Child;
import com.hongxun.design.acceptance.mode.GroupTitle;
import com.hongxun.design.acceptance.mode.ProblemR;
import com.hongxun.design.acceptance.mode.problem;
import com.hongxun.design.acceptance.mode.problemExist;
import com.hongxun.design.acceptance.mode.problemExistPhoto;
import com.hongxun.design.acceptance.view.PopWaterMark;
import com.hongxun.design.activitys.BaseActivity;
import com.hongxun.design.interfaces.HeadSecond;
import com.hongxun.design.listeners.ListenerSet;
import com.hongxun.design.mytools.IconSourse;
import com.hongxun.design.mytools.MString;
import com.hongxun.design.mytools.ShardPreferencesTool;
import com.hongxun.design.mytools.ToastShow;
import com.hongxun.design.ui.headandbottonpanel.HeadSecondControlPanel;
import com.hongxun.design.utils.DataUtil;
import com.hongxun.design.utils.PopwindowUtil;
import com.hongxun.design.utils.StringUtil;
import com.hongxun.design.utils.TimeUtil;
import com.hongxun.design.utils.fastjson.FastJsonUtil;
import com.hongxun.design.utils.projectdatautil.DataFactory;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by cqcqwu on 验收主界面
 */

public class AcceptActivity extends BaseActivity implements HeadSecond {
    private String title = null;
    private Handler handler = null;
    private ArrayList<String> poplist = null;
    private LinearLayout mainView;
    private Activity activity;
    //测试
    private ExpandableListView listView;
    private ExLvAdapter exLvAdapter;
    private ArrayList<GroupTitle> groups;
    private List<problem> libProAll;
    private List<problemExist> exPro;
    private ProblemR problemR;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_accept);
        this.title = getIntent().getStringExtra("0");
        this.activity = this;
//        this.poplist = DataUtil.getSSLBPopItem();
        this.poplist = new ArrayList<>();
        initData();
        initHander();
        findBar();
        initGroup();
    }

    private void initData() {
        libProAll = new ArrayList<>();//总量容器
        List<ProblemR> rList = DataFactory.getProblemRs(getApplicationContext());
        if (rList != null) {
            String ptId = MyApp.currExploration.getPt_id();
            for (ProblemR r : rList) {
                if (StringUtil.getNull(ptId).equals(r.getTermCode())) {
                    problemR = r;
                    break;
                }
            }
        }
        if (problemR == null) {
            ToastShow.showShort(getApplicationContext(), "当前点位不支持验收");
            finish();
        }
        //所有问题库
        String readLib = ShardPreferencesTool.read(getApplicationContext(), MString.library, "", 1);
        libProAll = JSON.parseArray(readLib, problem.class);
    }

    //默认头部
    private void initGroup() {
        GroupTitle groupTitle1 = new GroupTitle();
        groupTitle1.setTitlel(MString.existProblem);
        groupTitle1.setTitlec("");
        groupTitle1.setTitler("新增");
        GroupTitle groupTitle2 = new GroupTitle();
        groupTitle2.setTitlel(MString.problemLibrary);
        groupTitle2.setTitlec(" ");
        groupTitle2.setTitler("切换");
        groups = new ArrayList<>();
        groups.add(groupTitle1);
        groups.add(groupTitle2);

        exLvAdapter = new ExLvAdapter(this, groups, handler);
        listView.setAdapter(exLvAdapter);
    }

    //子项数据设置
    private void initList() {
        showWaitDialog(-1, "加载...");
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (GroupTitle group : groups) {
                    if (group.getTitlel().equals(MString.existProblem)) {
                        setExitPro(group);
                    } else if (group.getTitlel().equals(MString.problemLibrary)) {
                        setLibPro(group);
                    }
                }
                handler.sendEmptyMessage(7);
            }
        }).start();
    }

    //初始化问题库=全部问题-已存在的问题
    private void setLibPro(GroupTitle group) {
        poplist.clear();
        ArrayList<Child> arrayList = new ArrayList<>();
        if (libProAll != null) {
            for (problem problem : libProAll) {
                String tmNull = StringUtil.getNull(problem.getTermGuid());
                String str = StringUtil.getNull(problem.getBigType());
                if (tmNull.equals(problemR.getGuid())) {
                    if (!poplist.contains(str) && !TextUtils.isEmpty(str)) {
                        poplist.add(str);
                    }
                }
            }
            poplist.add("其他");
            for (problem problem : libProAll) {
                String tmNull = StringUtil.getNull(problem.getTermGuid());
                String btNull = StringUtil.getNull(problem.getBigType());
                if (tmNull.equals(problemR.getGuid())
                        && btNull.equals(poplist.get(0))) {
                    boolean isAdd = true;
                    for (problemExist exist : exPro) {
                        String cNull = StringUtil.getNull(exist.getPointId());//所属点位
                        String pointID = MyApp.currExploration.getExploration_id();
                        if (TextUtils.isEmpty(pointID)) {
                            pointID = MyApp.currExploration.getUuid();//离线时适用
                        }
                        if (cNull.equals(pointID)) {
                            String aNull = StringUtil.getNull(exist.getProblemGuid());//问题库guid
                            String bNull = StringUtil.getNull(exist.getStates());//问题状态
                            if (problem.getGuid().equals(aNull)
                                    && !bNull.equals("删除")) {
                                isAdd = false;
                                break;
                            }
                        }
                    }
                    if (isAdd) {
                        Child child = new Child();
                        child.setGuid_yh(problem.getGuid());
                        child.setOprtype(group.getTitlel());
                        child.setUrl(problem.getComputerUrls());
                        child.setCoPro(StringUtil.getNull(problem.getCommon()).trim());
                        child.setType(btNull + "-" + StringUtil.getNull(problem.getSmallType()));
                        arrayList.add(child);
                    }
                }
            }
        } else {
            libProAll = new ArrayList<>();
            poplist.add("其他");
        }
        group.setTitlec(poplist.get(0));
        group.setList(arrayList);
    }

    //已存在问题
    private void setExitPro(GroupTitle group) {
        List<problemExistPhoto> photos = DataFactory.getExProPh(getApplicationContext());
        exPro = DataFactory.getExPro(getApplicationContext());
        ArrayList<Child> arrayList = new ArrayList<>();
        if (!exPro.isEmpty()) {
            for (problemExist exist : exPro) {
                //当前点位;非删除状态;
                String pointID = MyApp.currExploration.getExploration_id();
                if (TextUtils.isEmpty(pointID)) {
                    pointID = MyApp.currExploration.getUuid();//离线时适用
                }
                boolean isDel = !StringUtil.getNull(exist.getStates()).equals("删除");
                if (exist.getPointId().equals(pointID) && isDel) {
                    Child child = new Child();
                    child.setGuid(exist.getGuid());
                    child.setOprtype(group.getTitlel());
                    //设置图片地址
                    String url = R.mipmap.zhanweidianshe + "";
                    if (photos != null)
                        for (problemExistPhoto photo : photos) {
                            if (exist.getGuid().equals(StringUtil.getNull(photo.getProblemExistGuid()))) {
                                url = photo.getPhoneUrls();
                                if (!new File(url).exists()) {
                                    url = photo.getComputerUrls();
                                }
                                break;
                            }
                        }
                    child.setUrl(url);
                    child.setExPro(StringUtil.getNull(exist.getExistDescribe()).trim());
                    child.setGuid_yh(StringUtil.getNull(exist.getProblemGuid()));//隐患库ID
                    child.setCoPro(StringUtil.getNull(exist.getResults()));//临时征用
                    child.setFindTime(TimeUtil.longToStr(exist.getFindTime()));
//                    child.setGuid_pt(exist.getPointId());
                    arrayList.add(child);
                }
            }
        } else {
            exPro = new ArrayList<>();
        }
        group.setList(arrayList);
    }

    @Override
    protected void onResume() {
        super.onResume();
        initList();
    }

    @Override
    public void addMore() {
        super.addMore();
    }

    @Override
    public void findBar() {
        listView = (ExpandableListView) findViewById(R.id.exListView);
        mainView = (LinearLayout) findViewById(R.id.pop_layout);
        HeadSecondControlPanel headsecond_layout = (HeadSecondControlPanel) findViewById(R.id.setpoint_layout);
        headsecond_layout.initHeadPanel(DataUtil.getsecondbean("", View.GONE, R.color.bar_right, ListenerSet.back,
                title, R.color.title, View.VISIBLE, IconSourse.BACK + "", View.VISIBLE));
        //头部点击：不收缩
        listView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                return true;
            }
        });
        //子项点击
        listView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                Child child = groups.get(groupPosition).getList().get(childPosition);
                childitemclick(child);
                return false;
            }
        });
        //长按效果
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                delExistChild(((ExpandableListView) parent), position);
                return true;
            }
        });

    }

    private void delExistChild(ExpandableListView parent, int position) {
        long packedPos = parent.getExpandableListPosition(position);
        int groupPosition = ExpandableListView.getPackedPositionGroup(packedPos);
        int childPosition = ExpandableListView.getPackedPositionChild(packedPos);
        if (childPosition >= 0) {
            final Child child = groups.get(groupPosition).getList().get(childPosition);
            if (StringUtil.getNull(child.getOprtype()).equals(MString.existProblem)) {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("删除提示");
                builder.setMessage("您生在试图删除：" + child.getExPro() + "\n确定删除吗?");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        delExistChild(child);
                        dialog.dismiss();
                    }
                });
                builder.setNegativeButton("取消", null);
                builder.show();
            }
        }
    }

    private void delExistChild(Child child1) {
        //先删除已存在的问题
        groups.get(0).getList().remove(child1);
        exLvAdapter.notifyDataSetChanged();
        for (problemExist exist : exPro) {
            if (child1.getGuid().equals(exist.getGuid())) {
                if (StringUtil.getNull(exist.getStates()).equals("新增")) {
                    exPro.remove(exist);
                    break;
                } else {
                    exist.setStates("删除");
                    break;
                }
            }
        }
        DataFactory.saveExPro(getApplicationContext(), FastJsonUtil.beanToJson(exPro));
        //加载本地问题库
        for (problem problem : libProAll) {
            //删除后，问题库展示时=当前点位类别+当前展示大类+那个问题
            if (problem.getTermGuid().equals(problemR.getGuid())
                    && problem.getBigType().equals(groups.get(1).getTitlec())
                    && child1.getGuid_yh().equals(problem.getGuid())) {
                Child child = new Child();
                child.setGuid_yh(problem.getGuid());
                child.setOprtype(groups.get(1).getTitlel());
                child.setUrl(problem.getComputerUrls());
                child.setCoPro(StringUtil.getNull(problem.getCommon()).trim());
                child.setType(StringUtil.getNull(problem.getBigType())
                        + "-"
                        + StringUtil.getNull(problem.getSmallType()));
                groups.get(1).getList().add(0, child);
                exLvAdapter.notifyDataSetChanged();
                break;
            }
        }

    }

    private void childitemclick(Child child) {
        switch (StringUtil.getNull(child.getOprtype())) {
            case MString.existProblem:
                for (problemExist exist : exPro) {
                    if (child.getGuid().equals(exist.getGuid())) {
                        Message message = handler.obtainMessage();
                        message.what = 6;
                        message.obj = exist;
                        handler.sendMessage(message);
                        break;
                    }
                }
                break;
            case MString.problemLibrary:
                for (problem pro : libProAll) {
                    if (StringUtil.getNull(child.getGuid_yh()).equals(pro.getGuid())) {
                        setPop(pro);
                        break;
                    }
                }
                break;
        }
    }

    //问题库更新：输入搜索时
    private void search_mc(String name) {
        List<Child> list = groups.get(0).getList();
        List<Child> listTemp = new ArrayList<>();
        for (problem problem : libProAll) {
            String aNull1 = StringUtil.getNull(problem.getCommon());//常见问题
            String aNull2 = StringUtil.getNull(problem.getTermGuid());//所属点位类型
            String aNull3 = StringUtil.getNull(problem.getBigType());//大类
            if (aNull2.equals(problemR.getGuid())
                    && aNull3.equals(groups.get(1).getTitlec())) {
                if (name.isEmpty() || aNull1.contains(name)) {
                    boolean isAdd = true;
                    for (Child child : list) {
                        if (problem.getGuid().equals(StringUtil.getNull(child.getGuid_yh()))) {
                            isAdd = false;
                            break;
                        }
                    }
                    if (isAdd) {
                        Child child = new Child();
                        child.setGuid_yh(problem.getGuid());
                        child.setOprtype(groups.get(1).getTitlel());
                        child.setUrl(MString.LOCALIMAGEHEAD + R.mipmap.zhanweidianshe);
                        child.setCoPro(aNull1);
                        child.setType(aNull3 + "-" + StringUtil.getNull(problem.getSmallType()));
                        listTemp.add(child);
                    }
                }
            }
        }
        groups.get(1).setList(listTemp);
        handler.sendEmptyMessage(2);
    }

    //问题库更新：切换大类时
    private void search_big(String big) {
        List<Child> list = groups.get(0).getList();
        List<Child> listTemp = new ArrayList<>();
        for (problem problem : libProAll) {
            String aNull1 = StringUtil.getNull(problem.getBigType());
            String aNull2 = StringUtil.getNull(problem.getTermGuid());
            //符合大类；符合点位类别；
            if (aNull1.equals(big) && aNull2.equals(problemR.getGuid())) {
                boolean isAdd = true;
                //排除已存在的；当前点位
                for (Child child : list) {
                    if (problem.getGuid().equals(StringUtil.getNull(child.getGuid_yh()))) {
                        isAdd = false;
                        break;
                    }
                }
                if (isAdd) {
                    Child child = new Child();
                    child.setGuid_yh(problem.getGuid());
                    child.setOprtype(groups.get(1).getTitlel());
                    child.setUrl(MString.LOCALIMAGEHEAD + R.mipmap.zhanweidianshe);
                    child.setCoPro(problem.getCommon());
                    child.setType(big + "-" + StringUtil.getNull(problem.getSmallType()));
                    listTemp.add(child);
                }
            }
        }
        groups.get(1).setList(listTemp);
        handler.sendEmptyMessage(2);
    }

    private void setPop(problem pro) {
        PopWaterMark patrolRange = new PopWaterMark(this, pro);
        patrolRange.showAtLocation(mainView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    private void initHander() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1://切换大类并设置数据
                        Integer index = Integer.valueOf(String.valueOf(msg.obj));
                        String big = poplist.get(index).toString().trim();
                        groups.get(1).setTitlec(big);
                        search_big(big);
                        break;
                    case 2://搜索结果处理
                        exLvAdapter.notifyDataSetChanged();
                        //默认全部展开
                        for (int i = 0; i < exLvAdapter.getGroupCount(); i++) {
                            listView.expandGroup(i);
                        }
                        break;
                    case 3://切换隐患库
                        PopwindowUtil.popChoice_JG_file(activity, mainView, poplist, handler, 1);
                        break;
                    case 4://新增记录
                        Intent intent4 = new Intent(activity, AcceptDetailActivity.class);
                        intent4.putExtra("0", title);
                        intent4.putExtra("1", "新增记录");
                        startActivity(intent4);
                        break;
                    case 5://搜索:手输值搜索
                        search_mc(String.valueOf(msg.obj));
                        break;
                    case 6://编辑记录
                        Intent intent6 = new Intent(activity, AcceptDetailActivity.class);
                        intent6.putExtra("0", title);
                        intent6.putExtra("1", "编辑记录");
                        intent6.putExtra("2", (problemExist) msg.obj);
                        startActivity(intent6);
                        break;
                    case 7://刷新数据
                        exLvAdapter.notifyDataSetChanged();
                        //默认全部展开
                        for (int i = 0; i < exLvAdapter.getGroupCount(); i++) {
                            listView.expandGroup(i);
                        }
                        hideWaitIngDialog();
                        break;
                    case 8://添加问题
                        Child child8 = (Child) msg.obj;
                        problem question = null;
                        for (problem problem : libProAll) {
                            if (child8.getGuid_yh().equals(problem.getGuid())) {
                                question = problem;
                                break;
                            }
                        }
                        if (question == null) return;
                        //展示数据：已存在问题
                        String uuid = UUID.randomUUID().toString();
                        Child child = new Child();
                        child.setGuid(uuid);
                        child.setOprtype(groups.get(0).getTitlel());
                        child.setUrl(MString.LOCALIMAGEHEAD + R.mipmap.zhanweidianshe);
                        child.setExPro(StringUtil.getNull(question.getCommon()));
                        child.setGuid_yh(question.getGuid());//隐患库ID
                        long timeMillis = System.currentTimeMillis();
                        child.setFindTime(TimeUtil.time(new Date(timeMillis)));
                        child.setCoPro("未处理");//临时征用
                        groups.get(0).getList().add(0, child);
                        exLvAdapter.notifyDataSetChanged();
                        //本地数据
                        problemExist exist = new problemExist();
                        exist.setGuid(uuid);
                        exist.setBigType(question.getBigType());
                        exist.setSmallType(question.getSmallType());
                        exist.setExistDescribe(StringUtil.getNull(question.getCommon()));
                        exist.setAdvice(StringUtil.getNull(question.getAnalysis()));
                        exist.setProblemGuid(question.getGuid());
                        exist.setFinder(MyApp.userInfo.getUsername());
                        exist.setFindTime(timeMillis);
                        exist.setNote("");
                        exist.setHandler("");//不默认
                        exist.setHandleTime(0);//不默认
                        exist.setResults("未处理");
                        exist.setAccepter(MyApp.userInfo.getUsername());
                        exist.setAcceptTime(timeMillis);
                        String pointID = MyApp.currExploration.getExploration_id();
                        if (TextUtils.isEmpty(pointID)) {
                            pointID = MyApp.currExploration.getUuid();//离线时适用
                        }
                        exist.setPointId(pointID);
                        exist.setProjectId(MyApp.currProject.getStage_id());
                        exist.setStates("新增");
                        exPro.add(exist);
                        DataFactory.saveExPro(getApplicationContext(), FastJsonUtil.beanToJson(exPro));
                        break;
                    case 9://验收
//                        Child child9 = groups.get(0).getList().get(msg.arg1);
                        Child child9 = (Child) msg.obj;
                        long timeMillis9 = System.currentTimeMillis();
                        for (problemExist problemExist : exPro) {
                            if (child9.getGuid().equals(problemExist.getGuid())) {
                                problemExist.setResults("已验收");
                                problemExist.setAcceptTime(timeMillis9);
                                if (problemExist.getStates().equals(MString.xmYTB))
                                    problemExist.setStates("修改");
                                break;
                            }
                        }
                        DataFactory.saveExPro(getApplicationContext(), FastJsonUtil.beanToJson(exPro));
                        break;
                }
            }
        };
    }
}
